// API配置
const API_BASE_URL = 'http://localhost:3001/api';

// 认证令牌管理
class AuthTokenManager {
  private static tokenKey = 'authToken';
  
  static getToken(): string | null {
    return localStorage.getItem(this.tokenKey);
  }
  
  static setToken(token: string): void {
    localStorage.setItem(this.tokenKey, token);
  }
  
  static clearToken(): void {
    localStorage.removeItem(this.tokenKey);
  }
}

// HTTP客户端封装
class HttpClient {
  private baseUrl: string;

  constructor(baseUrl: string) {
    this.baseUrl = baseUrl;
  }

  private async request<T>(endpoint: string, options: RequestInit = {}): Promise<T> {
    const url = `${this.baseUrl}${endpoint}`;
    
    // 获取认证令牌
    const token = AuthTokenManager.getToken();
    
    const config: RequestInit = {
      headers: {
        'Content-Type': 'application/json',
        ...(token ? { 'Authorization': `Bearer ${token}` } : {}),
        ...options.headers,
      },
      ...options,
    };

    try {
      const response = await fetch(url, config);
      
      if (!response.ok) {
        // 处理不同类型的HTTP错误
        let errorMessage = `HTTP error! status: ${response.status}`;
        
        // 尝试解析错误响应
        const contentType = response.headers.get('content-type');
        let errorData;
        
        if (contentType && contentType.includes('application/json')) {
          errorData = await response.json();
          errorMessage = errorData.message || errorMessage;
        } else {
          errorData = await response.text();
        }
        
        // 抛出包含更多详细信息的错误
        const error = new Error(errorMessage) as Error & { status?: number; data?: any };
        error.status = response.status;
        error.data = errorData;
        
        throw error;
      }
      
      return await response.json();
    } catch (error) {
      // 处理网络错误和其他异常
      if (error instanceof TypeError && error.message === 'Failed to fetch') {
        throw new Error('无法连接到服务器，请确保后端服务正在运行且网络连接正常');
      }
      
      // 处理中止请求的情况
      if (error instanceof DOMException && error.name === 'AbortError') {
        throw new Error('请求超时，请检查网络连接或重试');
      }
      
      // 处理JWT令牌过期
      if (error instanceof Error && error.message.includes('jwt expired')) {
        // 可以在这里添加刷新令牌的逻辑
        AuthTokenManager.clearToken();
        throw new Error('会话已过期，请重新登录');
      }
      
      // 处理身份验证失败
      if (error instanceof Error && 'status' in error && error.status === 401) {
        AuthTokenManager.clearToken();
        throw new Error('未授权访问，请先登录');
      }
      
      // 处理权限不足
      if (error instanceof Error && 'status' in error && error.status === 403) {
        throw new Error('权限不足，无法执行此操作');
      }
      
      // 处理资源未找到
      if (error instanceof Error && 'status' in error && error.status === 404) {
        throw new Error('请求的资源不存在');
      }
      
      // 处理验证错误
      if (error instanceof Error && 'status' in error && error.status === 400) {
        throw new Error('请求参数错误，请检查输入内容');
      }
      
      console.error('API请求失败:', error);
      throw error;
    }
  }

  public async get<T>(endpoint: string): Promise<T> {
    return this.request<T>(endpoint, { method: 'GET' });
  }

  public async post<T>(endpoint: string, data?: any): Promise<T> {
    return this.request<T>(endpoint, {
      method: 'POST',
      body: JSON.stringify(data),
    });
  }

  public async put<T>(endpoint: string, data?: any): Promise<T> {
    return this.request<T>(endpoint, {
      method: 'PUT',
      body: JSON.stringify(data),
    });
  }

  public async delete<T>(endpoint: string): Promise<T> {
    return this.request<T>(endpoint, { method: 'DELETE' });
  }

  // 专门用于文件上传的方法
  public async upload<T>(endpoint: string, formData: FormData): Promise<T> {
    const token = AuthTokenManager.getToken();
    
    return this.request<T>(endpoint, {
      method: 'POST',
      body: formData,
      headers: {
        ...(token ? { 'Authorization': `Bearer ${token}` } : {}),
      },
    });
  }
}

const httpClient = new HttpClient(API_BASE_URL);

// 认证相关API
export type User = {
  id: number;
  username: string;
  email: string;
};

export const authApi = {
  register: async (userData: { username: string; email: string; password: string }) => {
    const response = await httpClient.post<{ token: string; user: User }>('/auth/register', userData);
    // 保存令牌
    AuthTokenManager.setToken(response.token);
    return response;
  },
  
  login: async (credentials: { username: string; password: string }) => {
    const response = await httpClient.post<{ token: string; user: User }>('/auth/login', credentials);
    // 保存令牌
    AuthTokenManager.setToken(response.token);
    return response;
  },
  
  getProfile: () => 
    httpClient.get<User>('/auth/profile'),
    
  logout: () => {
    AuthTokenManager.clearToken();
  }
};

// 日记相关API
export type Diary = {
  id?: number;
  title: string;
  content: string;
  mood: string;
  tags?: string[];
  media?: {type: string; url: string}[];
  date?: string;
  created_at?: string;
};

export const diaryApi = {
  getAll: () => 
    httpClient.get<Diary[]>('/diaries/user/1'), // 假设默认用户ID为1，实际应该从认证信息中获取
  
  getById: (id: number) => 
    httpClient.get<Diary>(`/diaries/${id}`),
  
  create: (diary: Omit<Diary, 'id'>) => 
    httpClient.post<Diary>('/diaries', { user_id: 1, ...diary }), // 添加user_id
  
  update: (id: number, diary: Partial<Diary>) => 
    httpClient.put<Diary>(`/diaries/${id}`, diary),
  
  delete: (id: number) => 
    httpClient.delete(`/diaries/${id}`),
};

// 角色相关API
export type Character = {
  id?: number;
  name: string;
  emoji_data: string;
  personality: string;
};

export const characterApi = {
  create: (character: Omit<Character, 'id'>) => 
    httpClient.post<Character>('/characters', character),
  
  getById: (id: number) => 
    httpClient.get<Character>(`/characters/${id}`),
  
  update: (id: number, character: Partial<Character>) => 
    httpClient.put<Character>(`/characters/${id}`, character),
  
  delete: (id: number) => 
    httpClient.delete(`/characters/${id}`),
};

// 消息相关API
export type Message = {
  id?: number;
  content: string;
  sender: 'user' | 'character';
  timestamp?: string;
};

export const messageApi = {
  getByCharacterId: (characterId: number) => 
    httpClient.get<Message[]>(`/messages/character/${characterId}`),
  
  create: (message: Omit<Message, 'id'>) => 
    httpClient.post<Message>('/messages', message),
};

// 照片相关API
export const photoApi = {
  upload: (formData: FormData) => {
    return httpClient.upload('/photos/upload', formData);
  },
};

export default httpClient;